package com.woniu.controller;

import ch.qos.logback.core.rolling.helper.IntegerTokenConverter;
import com.woniu.common.CommonResult;
import com.woniu.entity.PersonUser;
import com.woniu.entity.UsedProduct;
import com.woniu.entity.UsedProductOrder;
import com.woniu.service.PersonUserService;
import com.woniu.service.UsedProductOrderService;
import com.woniu.service.UsedProductService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 二手市场订单表(UsedProductOrder)表控制层
 *
 * @author makejava
 * @since 2020-03-30 22:08:16
 */
@RestController
@RequestMapping("usedProductOrder")
public class UsedProductOrderController {
    /**
     * 服务对象
     */
    @Resource
    private UsedProductOrderService usedProductOrderService;

    @Resource
    PersonUserService personUserService;

    @Resource
    UsedProductService usedProductService;

    /**
     * 功能描述: 查询当前用户的所有订单
     * @Param: []
     * @Return: com.woniu.common.CommonResult
     * @Author: yanghan
     * @Date: 2020/4/2 17:11
     */
    @GetMapping("/findAllOrder")
    public CommonResult findAllOrder(){
        //获取当前登录用户Id
        //获取当前登录的用户的用户名
//        String name = cookieUtil.getName();
        String name = "admin";
        //查询用户Id
        PersonUser personUser = personUserService.findIdByName(name);
        try {
            List<UsedProductOrder> orderList = usedProductOrderService.findOrderByUserId(personUser.getId());
            return CommonResult.success("查询成功",orderList);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("查询失败");
        }

    }

    /**
     * 功能描述: 删除订单
     * @Param: [productId]
     * @Return: com.woniu.common.CommonResult
     * @Author: yanghan
     * @Date: 2020/3/31 9:58
     */
    @DeleteMapping("/deleteOrder/{productId}")
    public CommonResult deleteOrder(@PathVariable("productId")Integer productId){
        //获取当前登录用户Id
        //获取当前登录的用户的用户名
//        String name = cookieUtil.getName();
        String name = "admin";
        //查询用户Id
        PersonUser personUser = personUserService.findIdByName(name);
        Integer orderType = 1;
        //删除订单
        try {
            usedProductOrderService.deleteOrderByProductId(personUser.getId(),productId,orderType);
            return CommonResult.success("删除未付款商品成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("删除失败");
        }
    }

    /**
     * 功能描述: 获取订单数据
     * @Param: [productId]
     * @Return: com.woniu.common.CommonResult
     * @Author: yanghan
     * @Date: 2020/3/31 0:54
     */
    @GetMapping("/findOrderByProductId/{productId}")
    public CommonResult findOrderByProductId(@PathVariable("productId")Integer productId){
        //获取当前登录用户Id
        //获取当前登录的用户的用户名
//        String name = cookieUtil.getName();
        String name = "admin";
        //查询用户Id
        PersonUser personUser = personUserService.findIdByName(name);
        //订单类型(0:服务，1:二手市场)
        Integer i = 1;
        //根据用户Id、商品Id、订单类型查询数据
        try {
            UsedProductOrder order = usedProductOrderService.findOrderByProductId(personUser.getId(), productId, i);
            return CommonResult.success("查询订单成功",order);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("查询失败");
        }
    }

    /**
     * 功能描述: 生成订单信息，保存到数据库
     * @Param: [productId]
     * @Return: com.woniu.common.CommonResult
     * @Author: yanghan
     * @Date: 2020/3/31 0:21
     */
    @PostMapping("/createOrder/{productId}")
    public CommonResult createOrder(@PathVariable("productId")Integer productId){
        UsedProductOrder order = new UsedProductOrder();
        order.setProductId(productId);
        //获取当前登录用户Id
        //获取当前登录的用户的用户名
//        String name = cookieUtil.getName();
        String name = "admin";
        //查询用户Id
        PersonUser personUser = personUserService.findIdByName(name);
        //根据商品Id查询商品发布人的Id
        Integer issueUserId = usedProductService.findUserIdByProductId(productId);
        //判断当前登录用户是否购买商品用户
        if (issueUserId == personUser.getId()){
            return CommonResult.failed("不能购买自己发布的商品");
        }
        //根据当前用户Id、商品Id查询当前用户是否有此订单
        UsedProductOrder order1 = usedProductOrderService.findOrderByProductId(personUser.getId(), productId, 1);
        if (order1 == null){
            order.setUserId(personUser.getId());
            //设置为二手市场商品类型
            order.setProductOrderType(1);
            //根据商品id查询商品信息
            UsedProduct usedProduct = usedProductService.queryById(productId);
            //生成订单号
            String random = UUID.randomUUID().toString();
            String uuid = random.replaceAll("-", "");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String date = sdf.format(new Date());
            String ordernumber = uuid+date;
            order.setOrderNumber(ordernumber);
            order.setOrderName("用户:"+personUser.getNickname()+"的"+usedProduct.getProductName()+"订单");
            order.setOrderMoney(usedProduct.getSsellingPrice());
            System.out.println(order.toString());
            //订单状态（0：未支付，1：已支付）
            order.setOrderStatus(0);
            //将数据添加到数据库中
            try {
                usedProductOrderService.insert(order);
                return CommonResult.success("生成订单成功");
            } catch (Exception e) {
                e.printStackTrace();
                return CommonResult.failed("订单生成失败");
            }
        }
        return CommonResult.failed("当前商品已有未付款订单！");





    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public UsedProductOrder selectOne(Integer id) {
        return this.usedProductOrderService.queryById(id);
    }

}